package com.wondersgroup.tjfx.bo.impl.form;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mongodb.DBObject;
import com.mongodb.QueryBuilder;
import com.mongodb.util.JSON;
import com.quick.framework.boot.remoteResult.ResultObject;
import com.quick.framework.boot.repository.nosql.mongodb.inter.IMongoOperator;
import com.wondersgroup.tjfx.bo.inter.form.IForm;
import com.wondersgroup.tjfx.bo.inter.form.IFormPz;
import org.apache.commons.lang.StringUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.regex.Pattern;

/**
 * @Author WEI
 * @Description
 * @Date Created in 2018/06/15 10点30分57秒
 */
@Service
public class FormPzImpl implements IFormPz {

    @Autowired
    IForm form;

    @Autowired
    IMongoOperator mongoOperator;

    private final String type = "form";

    @Override
    public ResultObject saveForm(String formId, String jsonStr) {
        ResultObject ro = new ResultObject();
        try {
            if (StringUtils.isEmpty(formId)) {
                DBObject dbo = (DBObject) JSON.parse(jsonStr);
                formId = mongoOperator.executeInsertOneAsFile(type, dbo);
                ro.setInfo(type, formId);
            } else {
                DBObject dbo = (DBObject) JSON.parse(jsonStr);
                mongoOperator.executeUpdate(type, QueryBuilder.start("_id").is(new ObjectId(formId)), dbo);
            }
        } catch (Exception e) {
            ro.changeFaultState("保存失败");
            e.printStackTrace();
        }

        return ro;
    }

    @Override
    public JSONArray queryList(String key) {
        key = StringUtils.isEmpty(key) ? "" : key;
        JSONArray ary = new JSONArray();
        try {
            Pattern p = Pattern.compile("^.*" + key + ".*$", Pattern.CASE_INSENSITIVE);
            QueryBuilder query = QueryBuilder.start("title").regex(p);
            ary = mongoOperator.executeQuery(type, query, new String[]{"formId", "title"});
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ary;
    }

    @Override
    public JSONObject queryForm(String formId) {
        JSONObject result = new JSONObject();
        try {
            JSONArray ary = mongoOperator.executeQuery(type, QueryBuilder.start("_id").is(new ObjectId(formId)));
            if (ary.size() > 0) {
                result = ary.getJSONObject(0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public ResultObject deleteForm(String formId) {
        ResultObject ro = new ResultObject();
        try {
            mongoOperator.executeDeleteOne(type, QueryBuilder.start("_id").is(new ObjectId(formId)));
        } catch (Exception e) {
            e.printStackTrace();
            ro.changeFaultState(e.getLocalizedMessage());
        }
        return ro;
    }
}
